package com.neuedu.boot.security.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.neuedu.boot.security.config.CommonResult;
import com.neuedu.boot.security.entity.User;
import com.neuedu.boot.security.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;

@RestController
public class LoginController {

    @Autowired
    AuthenticationManager authenticationManager;
    
    @RequestMapping("/user/login")
    CommonResult login(String username,String password){


        //使用SpringSecurity的登录逻辑
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authRequest);

        if(authenticate != null){

            /**
             * 如果登录成功，生成jwt
             */
            //获取登录状态 登录成功之后authenticate 的Principal代表的的是 loadUserByUsername的返回结果
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

            User user = loginUser.getUser();//对一个数据库的那个实体

            //模拟更新最后一次登录时间
            user.setLastlogin(LocalDateTime.now());
            //TODO 模拟更新数据库

            //TODO ,跟Redis有段


            //使用用户身份生成jwt token ，发送个浏览器
            String secret = "abcdef";
            long longLastlogin = user.getLastlogin().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
            String token = JWT.create().
                    withClaim("userId", user.getUserId()).  //设置登录用户id
                    withClaim("username", user.getUsername()).  //设置登录的用户名
                    withClaim("lastlogin", longLastlogin).  //设置最后一次登录时间
                    sign(Algorithm.HMAC256(secret));

            return CommonResult.success(token);
        }else{
            return CommonResult.failed("用户名或密码不正确");
        }

    }



}
